<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      :btn-list="fullInfo.btnList"
      @returnBack="$emit('returnModify')"
    >
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
          >
            <template v-slot:form-supplierName>
              <el-input
                v-model="formInfo.data.supplierName"
                class="not-br not-mongolia"
                type="input"
                :disabled="true"
                placeholder="请选择供应商"
              >
                <template #append>
                  <el-icon @click="openSupplierWindow"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
          </page-form>
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <Tooltip :text="$t('detailInfo')"></Tooltip>
        </div>
        <div class="model-panel-body">
          <div class="filter-wrapper">
            <!-- 条件栏 -->
            <page-filter
              v-model:query="filterInfo.query"
              :filter-list="filterInfo.list"
            >
              <template v-slot:filter-addProduct>
                <el-button @click="addProduct">新增支付明细</el-button>
              </template>
              <template v-slot:filter-removeProduct>
                <el-button
                  :disabled="!canRemoveProduct"
                  @click="removeProduct()"
                  >删除支付明细</el-button
                >
              </template>
            </page-filter>
          </div>
          <div class="flex_full_item">
            <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
              <!-- 表格 -->
              <page-table
                ref="table"
                class="table-scroll-hidden"
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :summary-field-list="tableInfo.summaryFieldList"
                :tab-index="false"
                :query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :isDynamic="true"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-price="scope">
                  <span v-if="scope.row.price || scope.row.price === 0">
                    {{ scope.row.price + '元/' + scope.row.networkUnit }}
                  </span>
                  <span v-else>-</span>
                </template>
                <template v-slot:col-qty="scope">
                  {{ scope.row.qty + '' + scope.row.networkUnit }}
                </template>
              </page-table>
            </el-form>
          </div>
        </div>
      </div>
    </NewFullScreen>
    <!-- 选择产品 -->
    <addPayOrder
      v-if="productInfo.visible"
      v-model:show-dialog="productInfo.visible"
      :query="productInfo.query.queryMap"
      :query-params="productInfo.query.queryParams"
      :api="productInfo.api"
      :notDefaultProductSupplier="false"
      :table-key="productInfo.tableKey"
      @callback="selectProductCallback"
    />
    <select-supplier
      v-if="selectSupplierInfo.visible"
      v-model:show-dialog="selectSupplierInfo.visible"
      :check-box="false"
      :highlight-row="true"
      :query="selectSupplierInfo.query"
      :api="selectSupplierInfo.api"
      @callback="selectSupplierCallback"
    />
  </div>
</template>

<script setup name="payOrderModify">
import {
  pendPayOrderDetailPage,
  createProvincePayOrder,
  createProvincePayOrderAndSave,
  updateProvincePayOrder,
  provincePayOrderById,
  provincePayOrderDetailCustomizeListAll,
} from '@/api/province'
import { getCustomizeSetting } from '@/api/customize'
import addPayOrder from './addPayOrder.vue'
import SelectSupplier from '@/views/province/components/selectSupplier'
import { getMappingTripartiteSupplierPage } from '@/api/tripartite'
const emits = defineEmits()
const { proxy } = getCurrentInstance()
const props = defineProps(['visible', 'title', 'orderId'])
const formRefs = ref([])
const selectSupplierInfo = ref({
  visible: false,
  api: getMappingTripartiteSupplierPage,
  query: {
    sort: 'create_time desc',
    tsSystemCode:
      proxy.$store.state.permission.systemConfig
        .connect_purchase_platform_system,
    reserved1: '', //试剂or1耗材
  },
})
// return_type
const formInfo = ref({
  ref: null,
  data: {
    payType: 2,
    supplierName: '',
    supplierId: '',
  },
  fieldList: [
    {
      label: '支付类型',
      value: 'payType',
      type: 'select-model',
      code: 'province_purch_type',
      checkDefault: true,
    },
    {
      label: '供应商',
      value: 'supplierName',
      type: 'slot',
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {},
  },
  list: [
    { type: 'slot', label: '新增支付明细', value: 'addProduct' },
    { type: 'slot', label: '删除支付明细', value: 'removeProduct' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '150',
    btList: [
      {
        label: '删除',
        event: removeProduct,
        show: true,
      },
    ],
  },
})

const fullInfo = ref({
  btnList: [{ label: '保存并提交', event: saveAndSubmit, show: !props.orderId && proxy.$permission('provincePayOrder:saveAndSubmit') },{ label: '保存', event: save, show: true }],
})
//选择产品相关
const productInfo = ref({
  visible: false,
  api: pendPayOrderDetailPage,
  tableKey:
    'provincePayOrderAddPendPayOrder-com.slip.spd.entity.vo.provincePlatform.ProvincePendPayOrderDetailVO',
  query: {
    queryMap: {
      supplierId: {
        queryType: 'IN',
        value: null,
      },
      networkProductType: {
        queryType: 'IN',
        value: null,
      },
            type: {
        asTbName: 'core_product_new',
        columnName: 'type',
        queryResource: 0,
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 0,
      },
    },
    queryParams: {
      deliverOrderDetailIdNotIn: '',
    },
  },
  searchList: [],
})

const selectRow = ref('')

//用于显示取值
const systemConfig = ref(proxy.$store.state.permission.systemConfig)

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})

const canRemoveProduct = computed(() => {
  return tableInfo.value.selections.length
})

setData()
function setData() {
  let obj = {
    price: {
      label: '省采单价',
      value: 'price',
      type: 'slot',
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
    },
    qty: {
      label: '待结算数量',
      value: 'qty',
      type: 'slot',
      componentType: 'input',
      hidden: true,
    },
    commonName: {
      label: '通用名称',
      value: 'commonName',
      componentType: 'input',
      show: false,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...obj,
  })
  getCustomize()
}
// 触发事件
function handleEvent(event, data) {
  const _tableInfo = tableInfo.value
  switch (event) {
    case 'tableCheck':
      _tableInfo.selections = [...data]
      break
  }
}

function openSupplierWindow() {
  //选择供应商
  selectSupplierInfo.value.query.reserved1 = formInfo.value.data.payType
  selectSupplierInfo.value.visible = true
}
function selectSupplierCallback(data) {
  //选择供应商发回
  if (data && data.spdOrgId) {
    if (formInfo.value.data.supplierId !== data.spdOrgId) {
      formInfo.value.data['supplierId'] = data.spdOrgId
      formInfo.value.data['supplierName'] = data.name
      productInfo.value.query.queryMap.supplierId.value = data.spdOrgId
      tableInfo.value.data = []
    }
  } else {
    formInfo.value.data['supplierId'] = ''
    formInfo.value.data['supplierName'] = ''
    productInfo.value.query.queryMap.supplierId.value = ''
    tableInfo.value.data = []
  }
}

//添加产品按钮
function addProduct() {
  const _tableInfo = tableInfo.value
  let idNotIn = _tableInfo.data.map(function (item) {
    return item.provinceDeliverOrderDetailId
  })
  productInfo.value.query.queryParams.deliverOrderDetailIdNotIn =
    idNotIn.toString()
  productInfo.value.query.queryMap.networkProductType.value =
    formInfo.value.data.payType
    // 药品
    productInfo.value.query.queryMap.type = {
        asTbName: 'core_product_new',
        columnName: 'type',
        queryCategory: 'AND',
        queryResource: 0,
        queryType: 'EQUALS',
        value: formInfo.value.data.payType == 3 ? 4 : 0,
      }
  productInfo.value.visible = true
}

function selectProductCallback(rows) {
  console.log(rows)
  tableInfo.value.data = rows.concat(tableInfo.value.data)
}

//删除产品
function removeProduct(item) {
  if (item && item.id) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (obj) => obj.id !== item.id
    )
  } else {
    tableInfo.value.data = tableInfo.value.data.filter(
      (row) => !tableInfo.value.selections.includes(row)
    )
  }
}
function saveAndSubmit() {
  save(true)
}
function save(isSaveAndSubmit) {
  const _tableInfo = tableInfo.value
  proxy.$fn.checkForm(formRefs.value).then(() => {
    if (!_tableInfo.data.length) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '支付明细不能为空',
      })
      return
    }
    checkSave(isSaveAndSubmit)
  })
}
function checkSave(isSaveAndSubmit) {
  let params = proxy.$fn.deepClone(formInfo.value.data)
  params.details = tableInfo.value.data
  let api = props.orderId ? updateProvincePayOrder : isSaveAndSubmit === true ? createProvincePayOrderAndSave : createProvincePayOrder
  api(params).then((resp) => {
    if (resp && resp.success) {
      emits('returnModify', false)
      showDialog.value = false
    }
  })
}
function getrejectedOrderById(orderId) {
  provincePayOrderById(orderId).then((resp) => {
    if (resp && resp.success) {
      formInfo.value.data = resp.data
      productInfo.value.query.queryMap.supplierId.value = resp.data.supplierId

      getrejectedOrderDetails()
    }
  })
}
function getrejectedOrderDetails() {
  provincePayOrderDetailCustomizeListAll(filterInfo.value.query).then(
    (resp) => {
      if (resp && resp.success) {
        tableInfo.value.data = resp.data
        tableInfo.value.data.forEach((item) => {
          item.isConsignBusiness = item.isConsignment
          item.isConsignBusinessValue = item.isConsignmentValue
          item.supplierId = formInfo.value.data.supplierId
          item.supplierName = formInfo.value.data.supplierName
        })
      }
    }
  )
}

function getCustomize(update = undefined) {
  let _tableInfo = tableInfo.value
  let param = {
    tableKey:
      'provincePayOrderModify-com.slip.spd.entity.vo.provincePlatform.ProvincePayOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      _tableInfo.fieldList = proxy.$fn.setFieldList(
        _tableInfo.fieldList,
        data.detail
      )

      filterInfo.value.query.customizeUserVO = data
      filterInfo.value.query.queryMap.orderId.value = props.orderId
      if (update) {
        let arr = []
        for (let key in data.detail) {
          arr.push(data.detail[key])
        }
        let sortArr = []
        arr.forEach((item) => {
          if (item.sortControllerType === 1) {
            sortArr.push({
              prop: item.fieldName,
              order: 'ascending',
            })
          } else if (item.sortControllerType === 2) {
            sortArr.push({
              prop: item.fieldName,
              order: 'descending',
            })
          }
        })
        if (sortArr.length) {
          proxy.$refs.table.$refs.table.sort(sortArr[0].prop, sortArr[0].order)
        }
        return
      }
      if (props.orderId) {
        getrejectedOrderById(props.orderId)
      }
    }
  })
}
</script>

<style scoped lang="scss">
.model-panel-title {
  display: flex;
  align-items: center;
  .model-tips {
    display: flex;
    align-items: center;
    margin-left: 10px;
    color: #909399;
    .model-tips-nearly,
    .model-tips-expire {
      display: block;
      margin-left: 5px;
      width: 17px;
      height: 17px;
    }
    .model-tips-nearly {
      background: #fceacb;
    }
    .model-tips-expire {
      background: #f5e4e4;
    }
  }
}
:deep(.el-table) {
  .nearly-row {
    background: #fceacb;
  }
  .expire-row {
    background: #f5e4e4;
  }
  .cell-color {
    background: #f4aed9bd;
  }
}
</style>
